<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <!-- row col 布局 -->
      <el-row :gutter="20">
        <!-- gutter表间距 -->
        <el-col :span="8">
          <!--v-model绑定后，使用button点击事件就可搜索  clearable 清除文本功能  clear清除后发生的事件-->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getuserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getuserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisble = !addDialogVisble"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <!-- border 边框 stripe隔行变色 -->
      <el-table :data="userList" border stripe>
        <!-- type="index" 添加索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template> </el-table-column
        >>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRolesDialogVisiblefn(scope.row)"
              ></el-button>
            </el-tooltip>
          </template> </el-table-column
        >>
      </el-table>

      <!--current-page当前显示第几页  -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <!-- @close对话框关闭事件 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisble"
      width="50%"
      @close="addDialogClosed()"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="90px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" clearable></el-input>
        </el-form-item>

        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addForm.password" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile" clearable></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisble = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="EditDialogVisible"
      width="50%"
      @close="editDialogClose()"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
    >
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色:<el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogClosed()">取 消</el-button>
        <el-button type="primary" @click="savaRolesInfo()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        //合法邮箱
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    //验证手机号
    var checkMobile = (rule, value, cb) => {
      const regMobile = /([1][358][0-9][0-9]{8})|([1][4][37][0-9]{8})|([1][7][01367][0-9]{8})/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法电话号码'))
    }

    //username表单验证
    let usernameArr = [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      {
        min: 4,
        max: 15,
        message: '用户名称长度在4 到 15个字符',
        trigger: 'blur',
      },
    ]
    //email表单验证
    let emailArr = [
      { required: true, message: '请输入用户邮箱', trigger: 'blur' },
      {
        min: 6,
        max: 15,
        message: '邮箱长度在6 到 15个字符',
        trigger: 'blur',
      },
      { validator: checkEmail, trigger: 'blur' },
    ]
    //Mobile表单验证
    let mobileArr = [
      { required: true, message: '请输入用户电话', trigger: 'blur' },
      {
        min: 8,
        max: 15,
        message: '电话号码长度在8 到 15个字符',
        trigger: 'blur',
      },
      { validator: checkMobile, trigger: 'blur' },
    ]
    return {
      queryInfo: {
        query: '',
        //当前的页数
        pagenum: 1,
        //当前页面显示多少条数据
        pagesize: 2,
      },
      userList: [],
      total: 0,
      //控制添加对话框的显示与隐藏
      addDialogVisble: false,

      //添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },

      //添加表单验证规则
      addFormRules: {
        username: usernameArr,
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户密码长度在6 到 15个字符',
            trigger: 'blur',
          },
        ],
        email: emailArr,
        mobile: mobileArr,
      },

      //编辑对话框的显示与隐藏
      EditDialogVisible: false,

      //存储查询到的用户信息
      editForm: {},
      //编辑表单的验证规则
      editFormRules: {
        email: emailArr,
        mobile: mobileArr,
      },
      //分配角色对话框的隐藏与显示
      setRolesDialogVisible: false,

      //被分配角色的用户信息
      userInfo: [],

      //存储所有角色数据列表
      rolesList: [],
      //选中id
      selectedRoleId: '',
    }
  },

  created() {
    this.getuserList()
  },
  methods: {
    //获取用户列表
    async getuserList() {
      let { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('用户列表获取失败')
      }
      // console.log(res)
      this.total = res.data.total
      this.userList = res.data.users
      // console.log(this.total);
    },

    //监听pagesize改变
    handleSizeChange(newSize) {
      // console.log(newSize)
      //pagesize当前页面多少条数据
      this.queryInfo.pagesize = newSize
      this.getuserList()
    },

    // 监听页码值的改变
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getuserList()
    },

    //监听按钮状态改变
    async userStateChanged(userInfo) {
      // console.log(userInfo);
      // this.$http.put('users/:uId/state/:type')
      let { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      //  console.log(res);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功')
    },

    //对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    //添加用户事件
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (valid) {
          //可以发起网络请求
          const { data: res } = await this.$http.post('users', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功！！')
          this.addDialogVisble = false
          //刷新用户列表
          this.getuserList()
        }
      })
    },

    //点击编辑按钮弹出编辑对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
      this.EditDialogVisible = true
      console.log(res)
    },

    //监听编辑对话框关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },

    //用户修改事件
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败！！')
        }
        this.$message.success('更新成功')
        this.EditDialogVisible = false
        this.getuserList()
      })
    },

    //删除用户
    async removeUserById(id) {
      //  console.log(id);
      const res = await this.$confirm('此用户将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((error) => error)
      // console.log(res);
      //res为confirm则确认删除，为cancel为取消删除
      if (res === 'cancel') {
        this.$message.info('已取消删除')
      } else {
        //删除角色
        const { data: resdel } = await this.$http.delete('users/' + id)
        if (resdel.meta.status !== 200) {
          console.log(resdel)
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功!!!')
        this.getuserList()
      }
    },

    //分配角色对话框
    async setRolesDialogVisiblefn(userInfo) {
      this.userInfo = userInfo
      // console.log(this.userInfo)
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色列表获取失败')
      }
      this.$message.success('角色列表获取成功')
      this.rolesList = res.data
      this.setRolesDialogVisible = true
    },

    //分配角色
    async savaRolesInfo() {
      if (this.selectedRoleId == '') {
        return this.$message.error('请选择分配角色')
      }
      // console.log(this.userInfo.id,this.selectedRoleId);
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getuserList()
      this.setRolesDialogVisible = false
    },

    //关闭分配角色对话框
    setRolesDialogClosed() {
      this.selectedRoleId = '';
      this.userInfo=[];
      this.setRolesDialogVisible=false;
      
    },
  },
}
</script>


<style  scope>
</style>